<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="120px"
        class="demo-formData"
      >
        <el-row>
          <el-form-item label="姓名：" class="row-padding-bottom" prop="name">
            <el-select
              v-model="currentIdcard"
              class="mWidth"
              filterable
              clearable
              placeholder="请选择"
              @change="handleSelect"
            >
              <el-option
                v-for="(item, index) in nameOption"
                :key="index"
                :label="item.name"
                :value="item.idcard"
              >
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.idcard
                }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="身份证号："
            class="row-padding-bottom"
            prop="idcard"
          >
            <el-input
              class="sWidth"
              v-model="formData.idcard"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="证书编号："
            class="row-padding-bottom"
            prop="certificateNumber"
          >
            <el-input
              class="sWidth"
              v-model="formData.certificateNumber"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="发证日期：" prop="effectiveStartDate">
            <el-date-picker
              class="sWidth"
              type="date"
              placeholder="请选择发证日期"
              v-model="formData.effectiveStartDate"
              :picker-options="pickerOptions"
              @change="effectiveStartDateChange"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="到期日期：" prop="effectiveEndDate">
            <el-date-picker
              class="sWidth"
              type="date"
              placeholder="到期日期"
              v-model="formData.effectiveEndDate"
              disabled
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              prop="upLoadFile"
              label="证书附件："
              class="upLoadDomContainer"
              v-model="formData.fileList"
            >
              <uploadAnnex
                @getFileList="getFileList"
                :limitationFactor="limitationFactor"
                :upLoadFile="upLoadFile"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-model="formData.fileList">
            <uploadResult
              style="margin-left: 120px !important"
              :resultList="upLoadFile"
              @callBackResult="getFile"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              prop="empAppoint"
              label="劳资专管员企业任命文件："
              class="upLoadEmpAppointContainer"
              v-model="formData.empAppoint"
            >
              <uploadAnnex
                @getFileList="getEmpAppointList"
                :limitationFactor="limitationFactorTwo"
                @getFile="getEmpAppoint"
                :upLoadFile="empAppointList"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-model="formData.empAppoint">
            <uploadResult
              style="margin-left: 120px !important"
              :resultList="empAppointList"
              @callBackResult="getEmpAppoint"
            />
          </el-col>
        </el-row>
        <el-form-item class="submitBox">
          <el-button
            type="primary"
            class="commonBut saveBtn"
            id="addBtn"
            :loading="isSaveLoading"
            v-sdc
            :disabled="isDisabled"
            @click="saveForm"
            >提交</el-button
          >
          <el-button class="commonBut" @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import common from '../../kits/common'

export default {
  name: 'laborInfoAddCz',
  data() {
    var checkUpLoadFile = (rule, value, callback) => {
      if (this.upLoadFile.length == 0) {
        return callback(new Error('请上传证书附件'))
      } else {
        callback()
      }
    }
    var checkEmpAppoint = (rule, value, callback) => {
      if (this.empAppointList.length == 0) {
        return callback(new Error('请上传劳资专管员企业任命文件'))
      } else {
        callback()
      }
    }
    return {
      titleText: '添加劳资资质信息',
      back: true,
      nameOption: [], //姓名下拉
      //发证日期当天三年内
      pickerOptions: {
        disabledDate: (time) => {
          return (
            time.getTime() > Date.now() ||
            time.getTime() == Date.now() ||
            time.getTime() <
              new Date().setFullYear(new Date().getFullYear() - 3)
          )
        },
      },
      currentIdcard: '', //当前选中身份证号
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeOne', //自定义上传格式校验类型
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        messagetip:
          '请上传证书附件（必须包含证书编号内容、发证日期等信息），附件格式支持png，jpg，jpeg，最多上传10个附件', //自定义报错提示语
        methodTip:
          '请上传证书附件（必须包含证书编号内容、发证日期等信息），附件格式支持png，jpg，jpeg，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      limitationFactorTwo: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        fileId: 'managerUpLoadFile', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'managerUpLoadFileForm', //自定义id解决一个页面包含多个上传附件
        messagetip:
          '请上传劳资员任命证书，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义报错提示语
        methodTip:
          '请上传劳资员任命证书，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      upLoadFile: [],
      srcList: [],
      oldSrcList: [],
      formData: {
        name: '',
        idcard: '',
        certificateNumber: '',
        effectiveStartDate: '',
        effectiveEndDate: '',
        employeeId: '',
        files: [],
        empAppoint: [],
      },
      formRules: {
        name: [
          {
            required: true,
            message: '请选择姓名',
            trigger: ['blur', 'change'],
          },
        ],
        idcard: [
          {
            required: true,
            message: '请先选择姓名',
            trigger: ['blur', 'change'],
          },
        ],
        certificateNumber: [
          {
            required: true,
            pattern: /^[a-zA-Z0-9]{1,20}$/,
            message: '证书编号格式不正确',
            trigger: ['blur', 'change'],
          },
        ],
        effectiveStartDate: [
          {
            required: true,
            message: '请选择发证日期',
            trigger: 'change',
          },
        ],
        effectiveEndDate: [
          {
            required: true,
            message: '请先选择发证日期',
            trigger: 'change',
          },
        ],
        upLoadFile: [
          {
            required: true,
            validator: checkUpLoadFile,
            trigger: 'blur',
          },
        ],
        empAppoint: [
          {
            required: true,
            validator: checkEmpAppoint,
            trigger: 'blur',
          },
        ],
      },
      isSaveLoading: false, // 保存loading
      idcard: '',
      name: '',
      path: '',
      isDisabled: false,
      empAppointList: [],
    }
  },
  watch: {
    upLoadFile(val) {
      if (val.length > 0) {
        this.$refs.formData.clearValidate('upLoadFile')
      }
    },
    empAppointList(val) {
      if (val.length > 0) {
        this.$refs.formData.clearValidate('empAppoint')
      }
    },
  },
  created() {
    this.idcard = this.$route.query.idcard
    this.name = this.$route.query.name
    this.path = this.$route.query.path
    this.getNameOption()
  },
  methods: {
    goBack() {
      if (this.path == 'laborInfoAuditCz') {
        this.$router.push({
          path: '/home/employee/laborInfoAuditCz',
        })
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/employee/laborInfoAuditCz',
          newUrl: this.$router.currentRoute.fullPath,
        })
      } else {
        this.$router.push({
          path: '/home/employee/laborInfoCz',
        })
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/employee/laborInfoCz',
          newUrl: this.$router.currentRoute.fullPath,
        })
      }
    },
    getNameOption() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/contract/expand/detailbyworkertype',
        data: {
          type: '60', //劳资专管员
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.nameOption = response.data.result.list
            let item = this.nameOption.filter(
              (item) => item.idcard === this.idcard
            )
            if (this.idcard) {
              this.formData.name = this.name
              this.formData.idcard = this.idcard
              this.currentIdcard = this.idcard
              this.formData.employeeId = item[0].employeeId
              this.formData.projectId = response.data.result.projectId
              this.$nextTick(() => {
                this.$refs.formData.clearValidate('name')
                this.getDetail(this.formData.idcard)
              })
            }
          }
        })
        .catch((error) => {})
    },
    handleSelect(data) {
      if (data) {
        let item = this.nameOption.filter((item) => item.idcard === data)
        this.$nextTick(() => {
          this.formData.name = item[0].name
          this.formData.idcard = item[0].idcard
          this.formData.employeeId = item[0].employeeId
          this.$refs.formData.clearValidate('name')
          this.getDetail(this.formData.idcard)
        })
      } else {
        this.isDisabled = false
        this.formData.name = ''
        this.formData.idcard = ''
        this.formData.certificateNumber = ''
        this.formData.effectiveStartDate = ''
        this.formData.effectiveEndDate = ''
        this.formData.employeeId = ''
        this.upLoadFile = []
      }
    },
    effectiveStartDateChange() {
      let effectiveStartDate = this.formData.effectiveStartDate
      if (effectiveStartDate) {
        let year = +effectiveStartDate.substring(0, 4) + 3
        let expYear = effectiveStartDate.substring(4, 10)
        this.$nextTick(() => {
          this.formData.effectiveEndDate = year + expYear
          this.$refs.formData.clearValidate('effectiveEndDate')
        })
      } else {
        this.formData.effectiveEndDate = ''
      }
    },
    getFileList(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    getFile(val) {
      this.upLoadFile = val
    },
    getEmpAppointList(val) {},
    getEmpAppoint(val) {
      this.empAppointList = val
    },
    saveForm() {
      this.$refs.formData.validate((valid) => {
        this.formData.files = JSON.stringify(this.upLoadFile) //this.upLoadFile;
        this.formData.empAppointJson = JSON.stringify(this.empAppointList)
        if (valid) {
          this.isSaveLoading = true
          //若关闭审核功能，在点击提交后，弹窗提示：“添加后将直接展示到劳资专管员人员档案页”，最新的一条将直接覆盖历史数据。
          if (localStorage.getItem('loginType') === 'JC') {
            this.saveFormInfo()
          } else {
            this.judgeCloseAddit()
          }
        } else {
          return false
        }
      })
    },
    getDetail(idcard) {
      this.axios({
        method: 'post',
        url: 'api-e/cs/qualification/expand/getbyconditions',
        data: {
          idcard: idcard,
          type: '60',
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.isSaveLoading = false
            var data = response.data.result
            if (data.auditStatus === 1 && data.isEffective === true) {
              //已审核通过的且有效
              this.getDataImport(data)
              this.isDisabled = true
              this.$message({
                message: '该人员已存在劳资资质，无需重复添加',
                type: 'warning',
              })
            } else if (data.auditStatus === 0 && data.isEffective === true) {
              //待审核且有效
              this.getDataImport(data)
              this.isDisabled = true
              this.$message({
                message: '该人员已存在待审核的劳资资质信息，无需重复提交',
                type: 'warning',
              })
            } else {
              this.getDataOut()
              this.isDisabled = false
            }
          }
        })
        .catch((error) => {
          this.getDataOut()
        })
    },
    getDataImport(data) {
      this.formData.certificateNumber = data.certificateNumber
      this.formData.effectiveStartDate = data.effectiveStartDate
      this.formData.effectiveEndDate = data.effectiveEndDate
      this.upLoadFile = data.attachmentFiles
      this.empAppointList = data.empAppointFiles
      for (var i = 0; i < this.upLoadFile.length; i++) {
        this.srcList.push(this.upLoadFile[i].url)
        this.oldSrcList.push(this.upLoadFile[i].url)
      }
    },
    getDataOut() {
      this.formData.certificateNumber = ''
      this.formData.effectiveStartDate = ''
      this.formData.effectiveEndDate = ''
      this.upLoadFile = []
      this.isDisabled = false
      this.isSaveLoading = false
    },
    judgeCloseAddit() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/qualification/config/get',
        data: {
          type: '60',
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            //关闭审核功能
            if (
              response.data.result.length >= 1 &&
              response.data.result[0].value === 'DISABLE'
            ) {
              this.toConfirm()
            } else {
              this.saveFormInfo()
            }
          } else {
            this.isSaveLoading = false
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    toConfirm() {
      this.$confirm('添加后将直接展示到劳资专管员人员档案页', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.isSaveLoading = false
          this.saveFormInfo('employeeInfoC')
        })
        .catch(() => {
          //取消
          this.isSaveLoading = false
        })
    },
    saveFormInfo(type) {
      this.axios({
        method: 'post',
        url: 'api-e/cs/qualification/expand/add',
        data: {
          employeeId: this.formData.employeeId,
          certificateNumber: this.formData.certificateNumber,
          effectiveStartDate: this.formData.effectiveStartDate,
          effectiveEndDate: this.formData.effectiveEndDate,
          files: this.formData.files,
          empAppointJson: this.formData.empAppointJson,
        },
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '保存成功',
            })
            if (type === 'employeeInfoC') {
              //（建筑端）企业端/项目端的项目花名册-查看详情
              if (this.loginType === 'QY' || this.loginType === 'XM') {
                this.$router.push({
                  path: '/home/employee/employeeInfoC',
                  name: 'employeeInfoC',
                  query: {
                    employeeId: this.formData.employeeId,
                    projectId: this.formData.projectId,
                    path: 'projectEmployeeList',
                  },
                })
                this.$store.commit('CHANGE_SLIDER_NAME', {
                  oldUrl: '/home/employee/projectEmployeeQY',
                  newUrl: this.$router.currentRoute.fullPath,
                })
              } else {
                this.$router.push({
                  path: '/home/employee/employeeInfoC',
                  name: 'employeeInfoC',
                  query: {
                    employeeId: this.formData.employeeId,
                    path: 'JC',
                  },
                })
                this.$store.commit('CHANGE_SLIDER_NAME', {
                  oldUrl: '/home/employee/employeeTotalListJC',
                  newUrl: this.$router.currentRoute.fullPath,
                })
              }
            } else {
              this.goBack()
            }
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
  },
}
</script>
<style scoped lang="less">
.container {
  .mainCon {
    height: calc(100% - 50px);
    padding: 40px;
    overflow-y: auto;
    .submitBox {
      text-align: left;
      margin-top: 28px;
    }
    .uploadBox {
      position: relative;
      .uploadImg {
        width: 96px;
        height: 36px;
        color: #009588;
        border: 1px solid #009588;
        line-height: 10px;
      }
      .uploadImgState {
        font-size: 14px;
        color: #999999;
        margin-left: 12px;
      }
      .upLoadDom {
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        border-radius: 18px;
        input {
          width: 96px;
          height: 36px;
          border-radius: 18px;
          vertical-align: middle;
        }
        &:hover {
          .uploadImg {
            background-color: #0ff;
          }
        }
      }
    }
    .imgStyle {
      padding-left: 130px;
      li {
        position: relative;
        margin-right: 20px;
        margin-top: 10px;
        i {
          position: absolute;
          right: -6px;
          top: -10px;
          font-size: 20px;
        }
      }
    }
  }
}
form.el-form.demo-formData {
  display: inline-block;
  text-align: left;
  // .el-input,
  // .el-select {
  //     width: 320px !important;
  // }
  // .selectWidth {
  //     width: 100%;
  // }
}
// .el-main .el-form-item {
//     margin-bottom: 20px;
// }
.upLoadDomContainer .el-form-item__content {
  line-height: 36px !important;
}
.upLoadEmpAppointContainer /deep/ .el-form-item__label {
  line-height: 14px;
  margin-top: 5px;
}
#addBtn.el-button.is-disabled {
  background-color: gray !important;
  border-color: gray !important;
}
</style>
